using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour 
{
	SkeletonAnimation skeleton;
	int anim = 0;
	float speed = 100.0f;
	
	// Use this for initialization
	void Start () 
	{
		skeleton = GetComponent<SkeletonAnimation>();
		//skeleton.state.SetAnimation( "walk", true );
	}
	
	// Update is called once per frame
	void Update () 
	{
		if( Input.GetKey( KeyCode.Space) )
		{
			if( anim == 0 || anim == 1 )
			{
				skeleton.state.SetAnimation( "jump", false );
				anim = 2;
			}
		}
		
		if( anim == 2 && skeleton.state.IsComplete() )
		{
			//skeleton.state.ClearAnimation();
			anim = 0;
		}
		
		if( Input.GetKey( KeyCode.RightArrow) || Input.GetKey( KeyCode.LeftArrow) )
		{			
			if( anim == 0 )
			{
				skeleton.state.SetAnimation( "walk", true );
				anim = 1;
			}
		}
		else
		{
			if( anim == 1 )
			{
				skeleton.state.ClearAnimation();
				anim = 0;
			}
		}
		
		UpdateMove();
	}
	
	void UpdateMove()
	{	
		
		Vector3 Vec = transform.position;
		Vector3 Side = transform.localScale;
		RaycastHit hitInfo;
		
		Debug.DrawLine( Vec, Vec + (Vector3.down * 1000.0f));
		
		if( Physics.Raycast(Vec, Vector3.down, out hitInfo, 1000.0f ) )
		{
			Vec.y = hitInfo.point.y + 1;
		}
		
			
		if( Input.GetKey( KeyCode.RightArrow) )
		{
			Vec.x += speed * Time.deltaTime;
			
			if( Side.x < 0.0f )
				Side.x *= -1f;
		}
		
		if( Input.GetKey( KeyCode.LeftArrow) )
		{
			Vec.x -= speed * Time.deltaTime;
			
			if( Side.x > 0.0f )
				Side.x *= -1;
		}
		
		transform.position = Vec;
		transform.localScale = Side;
	}
}
